<?php

namespace app\common\model;

use catchAdmin\permissions\model\Users as UsersModel;
use app\common\model\search\FollowtaskSearch;
use catchAdmin\smstopic\model\SmsTopic;
use app\common\model\Follow as FollowModel;
use MongoDB\BSON\ObjectId;
use think\Collection;

class Followtask extends BaseModel
{
    use FollowtaskSearch;

    protected $name = "followtask";

    /**
     * 获取数据列表
     */
    public function getList()
	{
        $users = $this->getUserIds();
        $condition = [];
        if (!empty($users))
        {
            $condition[] = ["creator_id", "in", $users];
        }
        
        return  $this->mongoSearch()
                    ->order('created_at', 'desc')
                    ->field('id,follow_staff,taskname,status,endtime,creator_id,condition,starttime,search_request_id')
                    ->where($condition)
                    ->paginate($this->pageLimit)
                    ->each(function($item, $key){
                        $creator = (new UsersModel())->getOneData(['id' => $item['creator_id']], 'username');
                        $item['follow_staff_num'] = is_array($item['follow_staff'])?count($item['follow_staff']):1;
                        $item['creatorName'] = isset($creator['username'])?$creator['username']:'';

                        //计算随访计划完成进度
                        $total = (new FollowModel())->getConditionCount(['task_id' => new ObjectId($item['id'])]);#总数

                        $completed = (new FollowModel())->getConditionCount([['task_id', '=', new ObjectId($item['id'])], ['followStatus', '=', 1], ['is_effective', '=', 1]]);#已完成数

                        $already = (new FollowModel())->getConditionCount([['task_id', '=', new ObjectId($item['id'])], ['followStatus', '=', 1]]);#已随访数
                        
                        $item['progress'] = $total <> 0?round($already / $total * 100, 2):0;
                        $item['efficiency'] = $total <> 0?round($completed / $total * 100, 2).'%':'0%';
                        $item['taskVolume'] = $total;#随访任务量
                        return $item;
                    });
	}

    /**
     * 添加数据
     * 
     * @param array $param
     * @return string
     */
    public function addData(array $param): string
    {
        //添加时销毁自带的主键id
        unset($param['id']);
        return $this->save($param);
    }

    /**
     * 更新数据
     * @param array $param
     * @return bool
     */
    public function saveData($id, array $param): bool
    {
        $model = self::find($id);
        if ($model) {
            return $model->save($param);
        }
        return false;
    }

    /**
     * 我的随访任务
     * @param array $where
     * @param string $field
     * @param string $sortField
     */
    public function myFollowData(array $where=[], string $field="*", string $sortField="created_at")
    {
        $user = request()->user();
        $status = config('dictionary.followTaskStatus');
        return $this->mongoSearch([],[],['home','type'])
                ->where($where)
                ->field($field)
                ->order($sortField, 'desc')
                ->paginate($this->pageLimit)
                ->each(function ($item, $key) use($user, $status){
                    $item['statusName'] = $status[$item['status']];
                    $item['patient_num'] = (new FollowModel())->getConditionCount(['task_id' => new ObjectId($item['id'])]);
                    $already = (new FollowModel())->getConditionCount([['task_id', '=', new ObjectId($item['id'])], ['followStatus', '=', 1]]);#已随访数
                    $item['progress'] = $item['patient_num'] <> 0?round($already / $item['patient_num'] * 100, 2):0;
                    return $item;
                });
    }

    /**
     * 统计当前随访人员任务状态
     */
    public function countStatus()
    {
        $user = request()->user();

        //当前随访人员        
        $data['follow_personnel'] = $user['username']; 
        //统计未开始
        $data['notstart'] = $this->getConditionCount(['follow_staff.user_id' => $user['id'], 'status' => 0]);
        //统计进行中
        $data['conduct']  = $this->getConditionCount(['follow_staff.user_id' => $user['id'], 'status' => 1]);
        return $data;
    }

    /**
     * 更新数据
     * @param array $param
     * @return bool
     */
    public function saveStatus($id, array $param): bool
    {
        $model = self::find($id);

        if ($param['status'] == 1)
        {
            $param['starttime'] = date("Y-m-d");
        }else{
            $param['breaktime'] = date("Y-m-d");
            $param['establish_followtask_node.status'] = 2;
        }
        return $model->save($param);
    }

    /**
     * 获取我的随访任务
     */
    public function getMyTask()
    {
        return $this->where('follow_staff.user_id', request()->user()->id)->field('id,taskname')->select()->toArray();
    }

    /**
     * 获取随访任问卷模板
     */
    public function getTemplate($task_id)
    {
        $row = $this->where('id', $task_id)->field('template_id')->find()->toArray();
        return $row['template_id'];
    }    

    /**
     * 获取随访任务短信模板
     */
    public function getSms($task_id)
    {
        $row = $this->where('id', $task_id)->field('sms_id')->find()->toArray();
        
        $smsTopicIdArr =  $row['sms_id'];
        $ids=[];
        foreach($smsTopicIdArr as $k=>$v){
            $ids[] = $v["value"];
        }
        if(!empty($ids)){
                //根据主题id获取获取树型结构
               return   (new SmsTopic())->whereIn("id",$ids)->with("children")->select();
        }
        return [];
    }    

    /**
     * 条件获取数据
     * @param array $where 查询条件
     * @param string $field 字段
     */
    public function getOneData(array $where=[], string $field="*")
    {
        return  $this->where($where)->field($field)->find();
    }  

    /**
     * 获取条件匹配的统计数
     * @param array $where 条件
     * @return int
     */
    public function getConditionCount(array $where=[]): int
    {
        return  $this->where($where)->count();
    }   

    /**
     * 删除数据
     * @param string $id
     * @return bool
     */
    public function delData(string $id): bool
    {
        return  self::destroy($id);
    }

    /**
     * 获取键值数据
     *
     * @param array $where
     * @return array
     */
    public function getKvData(array $where=[]): array
    {
        return  $this->where($where)->column('id');
    }

    /**
     * 获取数据
     *
     * @param array $where
     * @param string $field
     * @return Collection
     */
    public function getConditionData(array $where=[], string $field="*"): Collection
    {
        return $this->where($where)->field($field)->select();
    }

}